<?php
namespace app\api\controller\wechat;
use app\admin\model\user\AdminOauth;
use app\common\controller\ApiBase;
use app\wechat\service\MiniProgram;
use think\Request;
class Oauth extends ApiBase
{
    public function get_code(Request $request)
    {
        $user = (new MiniProgram())->getCode($request->param('code',''));
        if(isset($user['session_key']) && isset($user['openid']))
        {
            $this->success("success:获取成功",'',$user);
        }
        $this->error("error:获取失败");
    }

    public function get_token()
    {
        $token = (new MiniProgram())->getAccessToken(true);
        //(new MiniProgram())->setAccessToken($token['access_token'],4);
        if($token)
        {
            $this->success("success:获取成功",'',$token);
        }else{
            $this->error("error:获取失败");
        }
    }

    public function decrypt_data()
    {
        $sessionKey    = $this->request->param("session_key");
        $encryptedData = $this->request->param("encrypted_data");
        $iv            = $this->request->param("iv");
        $result        = (new MiniProgram())->decryptData($sessionKey,$encryptedData,$iv,$data);
        if($result==1)
        {
            $this->success("success:获取成功",'',$data);
        }
        $this->error("error:获取失败");
    }

    public function get_unlimit()
    {
        $user_id  = $this->request->param("user_id",0,"intval");
        $third_party_user_id = $this->request->param("third_party_user_id",0,"intval");
        $pages = $this->request->param("pages",'');
        $user = [
            "user_id" => $user_id,
            "third_party_user_id" =>$third_party_user_id
        ];

        //检查用户有效性
        if($user_id)
        {
            $localUser = User::where("id",$user_id)->find();
            if(!$localUser) $user_id = 0;
        }
        if($third_party_user_id)
        {
            $third_party_user = AdminOauth::where("id",$third_party_user_id)->find();
            //Log::warning("htidss".json_encode($third_party_user));
            if(!$third_party_user) $third_party_user_id = 0;
        }

        //生成二维码
        $response = (new MiniProgram(get_option("datumdata")))->getUnlimit($user);

        if($response !="error")
        {
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse)
            {
                $files_path = DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR.'user/datumdata/share'.DIRECTORY_SEPARATOR;
                $up_path = dirname(app_path()).DIRECTORY_SEPARATOR.'public'.$files_path;
                $filename = $response->saveAs($up_path,$user_id.'_'.$third_party_user_id.'.png');

                //TODO：：上传到又拍云
                $data = [
                    "src" => _get_domain().$files_path.$filename
                ];
                $this->success("success:获取成功",$this->request->url(),$data);
            }else{
                $this->error("error:获取失败",$this->request->url(),'');
            }
        }
    }


}